
package com.shop.cloud.mall.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CacheConstants;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.mall.admin.service.*;
import com.shop.cloud.mall.common.constant.MallConstants;
import com.shop.cloud.mall.common.entity.*;
import com.shop.cloud.mall.admin.mapper.SupplierGoodsSpuMapper;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 供应商spu表
 *
 * @author
 * @date 2024-11-06 10:08:57
 */
@Service
@AllArgsConstructor
public class SupplierGoodsSpuServiceImpl extends ServiceImpl<SupplierGoodsSpuMapper, SupplierGoodsSpu> implements SupplierGoodsSpuService {

    private final SupplierGoodsSkuService supplierGoodsSkuService;
    private final SupplierGoodsSpuSpecService supplierGoodsSpuSpecService;
    private final SupplierGoodsSkuSpecValueService supplierGoodsSkuSpecValueService;
    private final FreightTemplatService freightTemplatService;
    private final GoodsSpuService goodsSpuService;

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        super.removeById(id);
        //删除SpuSpec、SkuSpecValue、Sku
        supplierGoodsSpuSpecService.remove(Wrappers.<SupplierGoodsSpuSpec>update().lambda()
                .eq(SupplierGoodsSpuSpec::getSpuId, id));
        supplierGoodsSkuSpecValueService.remove(Wrappers.<SupplierGoodsSkuSpecValue>update().lambda()
                .eq(SupplierGoodsSkuSpecValue::getSpuId, id));
        supplierGoodsSkuService.remove(Wrappers.<SupplierGoodsSku>update().lambda()
                .eq(SupplierGoodsSku::getSpuId, id));
        return true;
    }

    @SneakyThrows
    @Override
    public IPage<SupplierGoodsSpu> page1(IPage<SupplierGoodsSpu> page, SupplierGoodsSpu supplierGoodsSpu) {
        return baseMapper.selectPage1(page, supplierGoodsSpu);
    }

    @Override
    public SupplierGoodsSpu getById1(String id) {
        return baseMapper.selectById1(id);
    }

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save1(SupplierGoodsSpu supplierGoodsSpu) {
        this.saveHanddler(supplierGoodsSpu);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveBatch1(List<SupplierGoodsSpu> listSupplierGoodsSpu) {
        for (SupplierGoodsSpu item : listSupplierGoodsSpu) {
            if(MallConstants.FREIGHT_TYPE_2.equals(item.getFreightType())){
                FreightTemplat freightTemplat = freightTemplatService.getById(item.getFreightTemplatId());
                if(!item.getSupplierId().equals(freightTemplat.getShopId())){
                    return R.failed("商品【" + item.getName() +"】运费模板不正确");
                }
            }
            this.saveHanddler(item);
        }
        return R.ok();
    }
    void saveHanddler(SupplierGoodsSpu supplierGoodsSpu){
        supplierGoodsSpu.setPriceDown(null);
        supplierGoodsSpu.setPriceUp(null);
        baseMapper.insert(supplierGoodsSpu);
        List<SupplierGoodsSku> listSupplierGoodsSku = supplierGoodsSpu.getSkus();
        if(listSupplierGoodsSku !=null && listSupplierGoodsSku.size()>0){
            //新增sku
            listSupplierGoodsSku.forEach(supplierGoodsSku -> {
                priceUpDown(supplierGoodsSpu,supplierGoodsSku);
                supplierGoodsSku.setSupplierId(supplierGoodsSpu.getSupplierId());
                supplierGoodsSku.setSpuId(supplierGoodsSpu.getId());
                supplierGoodsSkuService.save(supplierGoodsSku);
                supplierGoodsSku.setId(supplierGoodsSku.getId());
            });
            baseMapper.updateById(supplierGoodsSpu);
            if(MallConstants.SPU_SPEC_TYPE_1.equals(supplierGoodsSpu.getSpecType())){//多规格处理
                supplierGoodsSpu.setId(supplierGoodsSpu.getId());
                addSpec(supplierGoodsSpu);
            }
        }
    }

    /**
     * 多规格处理
     * @param supplierGoodsSpu
     */
    void addSpec(SupplierGoodsSpu supplierGoodsSpu){
        //新增SpuSpec
        List<SupplierGoodsSpuSpec> listSupplierGoodsSpuSpec = supplierGoodsSpu.getSpuSpec().stream().map(spuSpec->{
            SupplierGoodsSpuSpec supplierGoodsSpuSpec = new SupplierGoodsSpuSpec();
            supplierGoodsSpuSpec.setSpuId(supplierGoodsSpu.getId());
            supplierGoodsSpuSpec.setSpecId(spuSpec.getId());
            return supplierGoodsSpuSpec;
        }).collect(Collectors.toList());
        for(int i = 0; i<listSupplierGoodsSpuSpec.size(); i++) {
            listSupplierGoodsSpuSpec.get(i).setSort(i);//设置排序字段
        }
        supplierGoodsSpuSpecService.saveBatch(listSupplierGoodsSpuSpec);
        //新增SkuSpecValue
        List<SupplierGoodsSkuSpecValue> listSupplierGoodsSkuSpecValue = new ArrayList<>();
        supplierGoodsSpu.getSkus().forEach(supplierGoodsSku -> {
            supplierGoodsSku.getSpecs().forEach(supplierGoodsSkuSpecValue -> {
                supplierGoodsSkuSpecValue.setSpuId(supplierGoodsSpu.getId());
                supplierGoodsSkuSpecValue.setSkuId(supplierGoodsSku.getId());
                listSupplierGoodsSkuSpecValue.add(supplierGoodsSkuSpecValue);
            });
        });
        for(int i = 0; i<listSupplierGoodsSkuSpecValue.size(); i++) {
            listSupplierGoodsSkuSpecValue.get(i).setSort(i);//设置排序字段
        }
        supplierGoodsSkuSpecValueService.saveBatch(listSupplierGoodsSkuSpecValue);
    }

    /**
     * 获取商品最高最低价
     * @param supplierGoodsSpu
     * @param supplierGoodsSku
     */
    void priceUpDown(SupplierGoodsSpu supplierGoodsSpu,SupplierGoodsSku supplierGoodsSku){
        if(CommonConstants.YES.equals(supplierGoodsSku.getEnable())){
            BigDecimal priceDown = supplierGoodsSpu.getPriceDown();
            if(priceDown == null || priceDown.compareTo(supplierGoodsSku.getSalesPrice()) == 1){
                supplierGoodsSpu.setPriceDown(supplierGoodsSku.getSalesPrice());
            }
            BigDecimal priceUp = supplierGoodsSpu.getPriceUp();
            if(priceUp == null || priceUp.compareTo(supplierGoodsSku.getSalesPrice()) == -1){
                supplierGoodsSpu.setPriceUp(supplierGoodsSku.getSalesPrice());
            }
        }
    }

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CacheConstants.MALL_SHOPPINGCART_CACHE, allEntries = true)
    public boolean updateById1(SupplierGoodsSpu supplierGoodsSpu) {
        supplierGoodsSpu.setPriceDown(null);
        supplierGoodsSpu.setPriceUp(null);
        List<SupplierGoodsSku> listSupplierGoodsSku = supplierGoodsSpu.getSkus();
        if(listSupplierGoodsSku !=null && listSupplierGoodsSku.size()>0){
            //先删除旧sku
            supplierGoodsSkuService.remove(Wrappers.<SupplierGoodsSku>update().lambda()
                    .eq(SupplierGoodsSku::getSpuId, supplierGoodsSpu.getId()));
            //新增sku
            listSupplierGoodsSku.forEach(supplierGoodsSku -> {
                priceUpDown(supplierGoodsSpu,supplierGoodsSku);
                supplierGoodsSku.setSupplierId(supplierGoodsSpu.getSupplierId());
                supplierGoodsSku.setSpuId(supplierGoodsSpu.getId());
                supplierGoodsSku.setTenantId(null);
                if(!supplierGoodsSkuService.saveOrUpdate(supplierGoodsSku)){
                    throw new RuntimeException("请重新提交");
                }
                supplierGoodsSku.setId(supplierGoodsSku.getId());
            });
            baseMapper.updateById(supplierGoodsSpu);
            //统一删除SpuSpec、SkuSpecValue
            supplierGoodsSpuSpecService.remove(Wrappers.<SupplierGoodsSpuSpec>update().lambda()
                    .eq(SupplierGoodsSpuSpec::getSpuId, supplierGoodsSpu.getId()));
            supplierGoodsSkuSpecValueService.remove(Wrappers.<SupplierGoodsSkuSpecValue>update().lambda()
                    .eq(SupplierGoodsSkuSpecValue::getSpuId, supplierGoodsSpu.getId()));
            if(MallConstants.SPU_SPEC_TYPE_1.equals(supplierGoodsSpu.getSpecType())) {//多规格处理
                addSpec(supplierGoodsSpu);
            }

        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shelf(String shelf, String ids) {
        //上下架供应商商品
        SupplierGoodsSpu supplierGoodsSpu = new SupplierGoodsSpu();
        supplierGoodsSpu.setShelf(shelf);
        baseMapper.update(supplierGoodsSpu,Wrappers.<SupplierGoodsSpu>lambdaQuery()
                .in(SupplierGoodsSpu::getId, Convert.toList(ids)));
        //下架相应的店铺商品
        if(CommonConstants.NO.equals(shelf)){
            //查询出该供应商商品关联的所有上架的店铺商品ID
            List<String> listIds = goodsSpuService.list(Wrappers.<GoodsSpu>query().lambda()
                    .eq(GoodsSpu::getShelf, CommonConstants.YES)
                    .in(GoodsSpu::getSupplierSpuId, ids)).stream().map(GoodsSpu::getId).collect(Collectors.toList());
            //下架店铺商品
            if(listIds.size() > 0){
                goodsSpuService.shelf(CommonConstants.NO, StrUtil.join(",", listIds));
            }
        }
    }
}
